<template>
  <div class="table-page-search-wrapper">
    <a-form layout="inline">
      <a-row :gutter="48">
        <a-col :md="6" :sm="24">
          <a-form-item :label="$t('all.autotext17')">
            <a-range-picker
              format="YYYY-MM-DD"
              :show-time="false"
              v-decorator="['range-time-picker']"
              :allowClear="true"
              @change="event_changeCreateTime"
              v-model="dateArr"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :md="6" :sm="12">
          <a-space>
            <a-button type="primary" @click="$refs.table.refresh(true)">
              {{ $t('all.autotext30') }}
            </a-button>
            <a-button @click="resetQueryParam">
              {{ $t('all.autotext340') }}
            </a-button>
          </a-space>
        </a-col>
        <a-col :md="12" :sm="12" align="right">
          <a-space>
            <a-button type="primary" v-if="$auth('PROJECT.PROJECT_BUDGET_ADD_V2')" @click="handleWarn">
              {{ $t('all.autotext1761') }}
            </a-button>
            <a-button type="primary" v-if="$auth('PROJECT.PROJECT_BUDGET_ADJUST_V2')" @click="budgetChange">
              {{ $t('all.autotext1550') }}
            </a-button>
            <a-button
              type="primary"
              v-if="
                $auth('PROJECT.PROJECT_BUDGET_ADD_V2') &&
                  $store.state.user.project.status !== 3
              "
              @click="handleAddBidgetVisible(true)"
            >
              {{ $t('all.autotext1209') }}
            </a-button>
            <a-button v-if="$auth('PROJECT.PROJECT_BUDGET_EXPORT_V2')" icon="export" @click="clickExport">
              {{ $t('all.autotext1014') }}
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-form>
    <s-table
      ref="table"
      size="default"
      :row-key="(record) => record.id"
      :data="loadData"
    >
      <a-table-column :title="$t('all.autotext334')" key="id" data-index="id">
        <template slot-scope="text, row, index">{{ index + 1 }}</template>
      </a-table-column>
      <a-table-column :title="$t('all.autotext1376')" key="budgetAmount" data-index="budgetAmount">
        <template slot-scope="text, record">
          ¥{{ record.budgetAmount.toFixed(2) }}
        </template>
      </a-table-column>
      <a-table-column
        v-if="serviceCharge"
        :title="$t('all.autotext1226')"
        key="studyAmount"
        data-index="studyAmount"
      >
        <template slot-scope="text, record">
          ¥{{ record.studyAmount.toFixed(2) }}
        </template>
      </a-table-column>
      <a-table-column
        v-if="serviceCharge"
        :title="$t('all.autotext449')"
        key="serverAmount"
        data-index="serverAmount"
      >
        <template slot-scope="text, record">
          ¥{{ record.serverAmount.toFixed(2) }}
        </template>
      </a-table-column>

      <a-table-column :title="$t('all.autotext1076')" key="applyAccount" data-index="applyAccount">
        <template slot-scope="text, record">
          {{
            (record.applyRole ? record.applyRole + ' - ' : '') +
              record.applyAccount
          }}
        </template>
      </a-table-column>
      <a-table-column :title="$t('all.autotext244')" key="createTime" data-index="createTime">
        <template slot-scope="text, record">
          {{ record.createTime | moment() }}
        </template>
      </a-table-column>
      <a-table-column :title="$t('all.autotext187')" align="center">
        <template slot-scope="record">
          <a v-if="$auth('PROJECT.PROJECT_BUDGET_DETAIL_V2')" @click="clickViewDetail(record, false, 'view')" style="margin-right: 10px">{{ $t('all.autotext568') }}</a>
        </template>
      </a-table-column>
    </s-table>
    <div class="total-wrap">
      <a-space :size="40">
        <div class="total-space">
          {{ $t('all.autotext151') }}:<span><em>¥</em>{{ (amountInfo.budget || 0).toFixed(2) }}</span>
        </div>
        <div class="total-space">
          {{ $t('all.autotext405') }}:<span><em>¥</em>{{ (amountInfo.studyAmount || 0).toFixed(2) }}</span>
        </div>
        <div class="total-space">
          {{ $t('all.autotext971') }}:<span><em>¥</em>{{ (amountInfo.totalBudget || 0).toFixed(2) }}</span>
        </div>
      </a-space>
    </div>
    <AddBudget
      ref="addBudget"
      :serviceCharge="serviceCharge"
      :visible="AddBudgetVisible"
      @ok="confirmAdd"
      @handleCancel="handleAddBidgetVisible(false)"
    />
    <ViewBudget
      ref="budgetRef"
      @handleOk="confirmView"
      :is-audit="isAudit"
      :viewType="viewType"
      :handType="handType"
    />
    <!-- 调整预算 -->
    <AdjustBudget
      ref="adjustBudget"
      :visible="adjustBudgetVisible"
      @ok="confirmAdjust"
      :originData="originData"
      @handleCancel="handleAdjustBidgetVisible(false)"
    />
    <warningSet ref="warnRef" />
  </div>
</template>
<script>
import storage from 'store'
import { CURRENT_PROJECT } from '@/store/mutation-types'
import { exportExcel } from '@/utils/util'
import {
  budgetList,
  addBudget,
  budgetExport,
  adjust,
  detailForAdjust
} from '@/api/overview/budget'
import { buildPaginationObj } from '@/components/Table'
import AddBudget from './addBudget'
import ViewBudget from './viewBudget'
import AdjustBudget from './adjustBudget.vue'
import warningSet from '@/views/entry/components/warningSet'
export default {
  components: { AddBudget, ViewBudget, AdjustBudget, warningSet },
  props: {
    datailId: {
      type: [Number, String],
      default: 0
    },
    budgetAmt: {
      type: [Number, String],
      default: 0
    }
  },
  data () {
    return {
      recordId: '',
      handType: '',
      record: {},
      dateArr: [],
      AddBudgetVisible: false,
      viewBudgetVisible: false,
      adjustBudgetVisible: false,
      queryParam: {},
      isAudit: false,
      loadData: (parameter) => {
        if (this.$auth('PROJECT.PROJECT_BUDGET_LIST_V2')) {
          return budgetList(Object.assign(parameter, this.queryParam))
            .then((res) => {
              this.amountInfo = res
              this.count = res.page ? res.page.length : 0
              return res.page
            })
            .catch(() => {})
        } else {
          return Promise.resolve(buildPaginationObj([]))
        }
      },
      amountInfo: {},
      count: 0,
      originData: {},
      viewType: ''
    }
  },
  computed: {
    serviceCharge () {
      const { serviceCharge, serviceChargePercent } =
        this.$store.state.user.project
      return serviceCharge || serviceChargePercent || 0
    }
  },
  created () {
    // this.queryParam.proId = this.$route.query.proId
    this.queryParam.proId = this.datailId
    this.detailForAdjust()
  },
  methods: {
    confirmAdd (data) {
      this.$refs.addBudget.btnLoading = true
      addBudget({
        proId: this.datailId,
        ...data
      })
        .then((res) => {
          this.$message.success(this.$t('all.autotext1243'))
          this.handleAddBidgetVisible(false)
          this.$refs.table.refresh(true)
        })
        .finally((_) => {
          this.$refs.addBudget.btnLoading = false
        })
    },
    confirmAdjust (data) {
      this.$refs.adjustBudget.btnLoading = true
      if (Number(data.studyAmount) === 0 && Number(data.serverAmount) === 0) {
        this.$message.error(this.$t('all.autotext1672'))
        this.$refs.adjustBudget.btnLoading = false
        return false
      }
      adjust({
        proId: this.datailId,
        studyAmount:
          Number(data.studyAmount) === 0 ? 0 : `-${data.studyAmount}`,
        serverAmount:
          Number(data.serverAmount) === 0 ? 0 : `-${data.serverAmount}`
      })
        .then((res) => {
          this.$message.success(this.$t('all.autotext529'))
          this.handleAdjustBidgetVisible(false)
          this.$refs.table.refresh(true)
        })
        .finally((_) => {
          this.$refs.adjustBudget.btnLoading = false
        })
    },
    clickExport () {
      budgetExport({
        ...this.queryParam,
        proId: this.datailId
      }).then((res) => {
        exportExcel(this.$t('all.autotext402'), res)
      })
    },
    handleAddBidgetVisible (flag = false) {
      this.AddBudgetVisible = flag
    },
    handleViewBidgetVisible (flag = false) {
      this.viewBudgetVisible = flag
    },
    handleAdjustBidgetVisible (flag = false) {
      this.adjustBudgetVisible = flag
    },
    budgetChange () {
      this.detailForAdjust(true)
    },
    clickViewDetail (record, flag, handleType) {
      this.handType = handleType
      this.record = record
      this.recordId = record.id
      this.isAudit = flag
      if (record.budgetAmount <= 0) {
        this.viewType = 'adjustBudget'
      } else {
        this.viewType = 'addBudget'
      }
      this.$refs.budgetRef.open(this.recordId)
    },
    confirmView () {
      // this.$emit('handleOk')
      this.$refs.table.refresh(true)
    },
    event_changeCreateTime (date, dateString) {
      this.queryParam.startTime = dateString[0]
      this.queryParam.endTime = dateString[1]
    },
    // 点击重置按钮清空查询
    resetQueryParam () {
      this.dateArr = []
      this.queryParam = { proId: this.datailId }
      this.$refs.table.refresh(true)
    },
    // 获取弹框默认值
    async detailForAdjust (flag) {
      const res = await detailForAdjust({ proId: this.datailId })
      console.log(res)
      this.originData = res
      for (let key in this.originData) {
        if (!this.originData[key]) {
          this.originData[key] = 0
        }
      }
      if (flag) this.handleAdjustBidgetVisible(true)
    },
    handleWarn () {
      const pro = storage.get(CURRENT_PROJECT)
      const businessCode = JSON.parse(pro).businessCode
      this.$refs.warnRef.open(businessCode, 2)
    }
  }
}
</script>
<style lang="less" scoped>
.budgetView {
  margin: 10px 0 20px 0;
  font-size: 18px;
  span {
    margin-right: 10px;
  }
}
.total-wrap {
  margin-top: 20px;
  em {
    font-style: normal;
    font-size: 16px;
  }
  .total-space > span {
    font-size: 18px;
    font-weight: bold;
    margin-left: 8px;
  }
}
</style>
